/**
 * 课程表相关工具函数
 */

import { Course, ProcessedCourse } from '../types/course';
import { ScheduleCell, TimeSlot } from '../types/schedule';
import { getCourseColor } from './colorUtils';

/**
 * 根据当前周次和周次模式过滤课程
 * @param courses 课程列表
 * @param currentWeek 当前周次
 * @returns 过滤后的课程列表
 */
export const filterCoursesByWeek = (courses: Course[], currentWeek: number): Course[] => {
  return courses.filter(course => {
    const { start, end, pattern } = course.weeks;

    const inRange = currentWeek >= start && currentWeek <= end;
    if (!inRange) return false;

    switch (pattern) {
      case 'every':
        return true;
      case 'odd':
        return currentWeek % 2 !== 0;
      case 'even':
        return currentWeek % 2 === 0;
      default:
        return false;
    }
  });
};

/** 时间段定义 */
export const TIME_SLOTS: TimeSlot[] = [
  { id: 1, label: '1-2', startSection: 1, endSection: 2 },
  { id: 2, label: '3-4', startSection: 3, endSection: 4 },
  { id: 3, label: '5-6', startSection: 5, endSection: 6 },
  { id: 4, label: '7-8', startSection: 7, endSection: 8 },
  { id: 5, label: '9-10', startSection: 9, endSection: 10 },
  { id: 6, label: '11-12', startSection: 11, endSection: 12 },
];

/** 获取节次对应的时间段索引 */
export const getSectionIndex = (section: number): number => {
  return Math.floor((section - 1) / 2);
};

/**
 * 处理课程数据，添加颜色和位置信息
 * @param courses 原始课程列表
 * @returns 处理后的课程列表
 */
export const processCourses = (courses: Course[]): ProcessedCourse[] => {
  const usedColors = new Map<string, string>();
  let animationIndex = 0;

  return courses.map((course, index) => {
    const dayIndex = course.day_of_week - 1; // 转换为0-6索引
    const sectionIndex = getSectionIndex(course.section.start);

    const color = getCourseColor(index, dayIndex, sectionIndex, usedColors);
    const positionKey = `${dayIndex}-${sectionIndex}`;
    usedColors.set(positionKey, color);

    const rowSpan = course.section.end - course.section.start + 1;
    const actualRowSpan = Math.ceil(rowSpan / 2);

    return {
      ...course,
      color,
      animationDelay: animationIndex++ * 100,
      gridPosition: {
        row: sectionIndex + 2,
        column: dayIndex + 2,
        rowSpan: actualRowSpan,
      },
    };
  });
};

/**
 * 创建课程表网格数据
 * @param courses 处理后的课程列表
 * @returns 7x6的网格数据
 */
export const createScheduleGrid = (courses: ProcessedCourse[]): ScheduleCell[][] => {
  const grid: ScheduleCell[][] = Array.from({ length: 7 }, (_, dayIndex) =>
    Array.from({ length: 6 }, (_, sectionIndex) => ({
      course: null,
      day: dayIndex + 1,
      section: sectionIndex + 1,
      isSpanned: false,
    }))
  );

  courses.forEach(course => {
    const dayIndex = course.day_of_week - 1;
    const startSectionIndex = getSectionIndex(course.section.start);
    const endSectionIndex = getSectionIndex(course.section.end);

    if (dayIndex >= 0 && dayIndex < 7 && startSectionIndex >= 0 && startSectionIndex < 6) {
      grid[dayIndex][startSectionIndex] = {
        course,
        day: dayIndex + 1,
        section: startSectionIndex + 1,
        isSpanned: false,
        color: course.color,
      };

      for (let i = startSectionIndex + 1; i <= endSectionIndex && i < 6; i++) {
        grid[dayIndex][i] = {
          course: null,
          day: dayIndex + 1,
          section: i + 1,
          isSpanned: true,
          color: course.color,
        };
      }
    }
  });

  return grid;
};

/**
 * 获取课程的显示文本
 * @param course 课程信息
 * @returns 显示文本对象
 */
export const getCourseDisplayText = (course: Course) => {
  return {
    name: course.course_name,
    location: course.location.name,
    teacher: course.teacher.name || '未知教师',
    time: `${course.section.start}-${course.section.end}节`,
  };
};

/**
 * 计算总周数
 * @param courses 课程列表
 * @returns 总周数
 */
export const calculateTotalWeeks = (courses: Course[]): number => {
  if (!courses || courses.length === 0) return 16; // 默认16周
  return courses.reduce((max, course) => (course.weeks.end > max ? course.weeks.end : max), 0) || 16;
};
